package com.js.data.system.service.impl;

import com.js.data.system.entity.SysUserRole;
import com.js.data.system.mapper.SysUserRoleMapper;
import com.js.data.system.vo.SimpleRoleVO;
import com.js.data.system.vo.SimpleUserVO;
import com.js.data.system.service.UserRoleService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户角色关联 服务实现类
 * </p>
 *
 * @author wujj
 * @since 2022-09-06
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements UserRoleService {


    /**
     * 根据用户id删除
     *
     * @param userId 用户id
     */
    @Override
    public void removeByUserId(Long userId) {
        lambdaUpdate().eq(SysUserRole::getUserId, userId).remove();
    }

    /**
     * 根据角色id删除
     *
     * @param roleId 角色id
     */
    @Override
    public void removeByRoleId(Long roleId) {
        lambdaUpdate().eq(SysUserRole::getRoleId, roleId).remove();
    }

    /**
     * 批量入库
     *
     * @param roleIds 角色id
     * @param userId  用户uid
     */
    @Override
    public void saveBatchToDB(List<Long> roleIds, Long userId) {
        if (CollectionUtils.isNotEmpty(roleIds)) {
            List<SysUserRole> userRoles = new ArrayList<>();
            roleIds.forEach(roleId -> {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                userRoles.add(ur);
            });
            saveBatch(userRoles);
        }
    }

    /**
     * 批量删除用户
     *
     * @param userIds 用户ids
     */
    @Override
    public void removeByUserIds(List<Long> userIds) {
        lambdaUpdate().in(SysUserRole::getUserId, userIds).remove();
    }

    /**
     * 获取用户角色
     *
     * @param userId 用户id
     * @return List<SimpleRoleVO>
     */
    @Override
    public List<SimpleRoleVO> listUserRoleByUid(Long userId) {
        return getBaseMapper().selectRoleByUid(userId);
    }

    /**
     * 根据角色查找关联用户列表
     *
     * @param roleId 角色id
     * @return List<SimpleUserVO>
     */
    @Override
    public List<SimpleUserVO> listSimpleUserByRoleId(Long roleId) {
        return getBaseMapper().selectUserByRoleId(roleId);
    }

    /**
     * 根据用户uid查找角色id
     *
     * @param userId 用户uid
     * @return Set<Integer>
     */
    @Override
    public Set<Long> listUserRoleIds(Long userId) {
        return lambdaQuery()
                .eq(SysUserRole::getUserId, userId).list()
                .stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toSet());
    }
}
